package cn.itcast.bos.web.action;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.Queue;
import javax.jms.Session;
import javax.jws.WebParam.Mode;
import javax.servlet.ServletContext;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import org.apache.commons.lang3.RandomStringUtils;
import org.apache.cxf.jaxrs.client.WebClient;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.aspectj.apache.bcel.classfile.Constant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

import cn.itcast.bos.constant.Constants;
import cn.itcast.bos.utils.MailUtils;
import cn.itcast.crm.domain.Customer;

@ParentPackage("json-default")
@Namespace("/")
@Controller
@Scope("prototype")
public class CustomerAction extends ActionSupport implements
		ModelDriven<Customer> {
	@Autowired
	private JmsTemplate jmsTemplate;
	@Autowired
	private Queue queueDestination;

	private Customer c = new Customer();

	@Override
	public Customer getModel() {
		// TODO Auto-generated method stub
		return c;
	}

	@Action(value = "customer_sendSms")
	public String sendSms() {
		// 生成短信验证码
		final String code = RandomStringUtils.randomNumeric(4);
		// 将验证码保存到session中
		ServletActionContext.getRequest().getSession()
				.setAttribute(c.getTelephone(), code);
		// 打印出验证码
		System.out.println("验证码为" + code);
		jmsTemplate.send(queueDestination, new MessageCreator() {
			final String msg = "验证码为" + code;

			@Override
			public Message createMessage(Session session) throws JMSException {
				MapMessage message = session.createMapMessage();
				message.setString("telephone", c.getTelephone());
				message.setString("msg", msg);
				return message;
			}
		});
		return NONE;

	}

	// 属性驱动,获取前台传送的验证码
	private String checkcode;

	public void setCheckcode(String checkcode) {
		this.checkcode = checkcode;
	}

	// 用户注册的方法
	@Action(value = "customer_regist", results = {
			@Result(name = "success", type = "redirect", location = "signup-success.html"),
			@Result(name = "input", type = "redirect", location = "signup.html") })
	public String regist() {
		String checkcodeSession = (String) ServletActionContext.getRequest()
				.getSession().getAttribute(c.getTelephone());
		// 判断前台传送的验证码是否与后台生成的验证码一致
		if (checkcodeSession == null || !checkcodeSession.equals(checkcode)) {
			System.out.println("验证码错误");
			return INPUT;
		} else {

			WebClient
					.create("http://localhost:9999/crm_management"
							+ "/services/customerService/customer")
					.type(MediaType.APPLICATION_JSON).post(c);
			// 发送一封激活邮件
			// 生成激活码
			String activecode = RandomStringUtils.randomNumeric(32);

			// 将激活码保存到redis，设置24小时失效
			redisTemplate.boundValueOps(c.getTelephone()).set(activecode, 24,
					TimeUnit.HOURS);

			// 调用MailUtils发送激活邮件
			String content = "尊敬的客户您好，请于24小时内，进行邮箱账户的绑定，点击下面地址完成绑定:<br/><a href='"
					+ MailUtils.activeUrl
					+ "?telephone="
					+ c.getTelephone()
					+ "&activecode=" + activecode + "'>速运快递邮箱绑定地址</a>";
			MailUtils.sendMail("速运快递激活邮件", content, c.getEmail());
			System.out.println("注册成功");
			return SUCCESS;
		}
	}

	// 属性驱动,获取前台传送的邮箱验证码
	private String activecode;
	@Autowired
	private RedisTemplate<String, String> redisTemplate;

	public void setActivecode(String activecode) {
		this.activecode = activecode;
	}

	@Action(value = "customer_activeMail")
	public String activeMail() throws IOException {
		// 防止response显示乱码
		ServletActionContext.getResponse().setContentType(
				"text/html;charset=utf-8");
		// 接收前台验证码
		String activecodeRedis = redisTemplate.boundValueOps(c.getTelephone())
				.get();
		if (activecodeRedis == null || !activecodeRedis.equals(activecode)) {
			ServletActionContext.getResponse().getWriter().print("激活失败");
		} else {
			// 查询数据库看客户是否已经绑定
			Customer customer = WebClient
					.create("http://localhost:9999/crm_management"
							+ "/services/customerService/customer/telephone/"
							+ c.getTelephone())
					// 路径+请求参数,请求参数为页面注册的电话号码
					.type(MediaType.APPLICATION_JSON)
					.accept(MediaType.APPLICATION_JSON).get(Customer.class);
			// 判断
			if (customer.getType() == null || customer.getType() != 1) {
				// 没有绑定则进行绑定
				WebClient
						.create("http://localhost:9999/crm_management"
								+ "/services/customerService/customer/updatetype/"
								+ c.getTelephone())
						// 修改绑定类型,根据电话号码
						.type(MediaType.APPLICATION_JSON)
						.accept(MediaType.APPLICATION_JSON).get();
				ServletActionContext.getResponse().getWriter().print("绑定成功");
			} else {
				ServletActionContext.getResponse().getWriter().print("不能重复绑定");
			}
			// 删除激活码
			redisTemplate.delete(c.getTelephone());
		}
		return NONE;
	}

	/**
	 * 用户登陆
	 */
	@Action(value = "customer_login", results = {
			@Result(name = "login", location = "login.html", type = "redirect"),
			@Result(name = "success", location = "index.html#/myhome", type = "redirect") })
	public String login() {
		Customer customer = WebClient
				.create(Constants.CRM_MANAGEMENT_URL
						+ "/services/customerService/customer/login?telephone="
						+ c.getTelephone() + "&password=" + c.getPassword())
				.type(MediaType.APPLICATION_JSON)
				.accept(MediaType.APPLICATION_JSON).get(Customer.class);
		//判断customer是否为空
		if(customer==null){
			//登陆失败
			return LOGIN;
		}else{
			//登陆成功
			//把用户存入session中
			ServletActionContext.getRequest().getSession().setAttribute("customer", customer);
			return SUCCESS;
		}
	}
}
